package store.wetravel.web.backend.scenicSpot.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import store.wetravel.common.Const;
import store.wetravel.common.ServerResponse;
import store.wetravel.pojo.User;
import store.wetravel.web.user.service.IUserService;

import javax.servlet.http.HttpSession;

/**
 * Created by xinlong on 2017/10/25.
 */
@Controller
@RequestMapping("/manage/user")
public class UserManageController {

    @Autowired
    @Qualifier("iUserService")
    private IUserService iUserService;

    @RequestMapping(value = "login.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> login(String username, String password, HttpSession session){
        ServerResponse<User> response = iUserService.login(username,password);
        if(response.isSuccess()){
            User user = response.getData();
            if(user.getRole() == Const.Role.ROLE_ADMIN){
                //说明登录的是管理员
                session.setAttribute(Const.CURRENT_USER,user);
                return response;
            }else{
                return ServerResponse.createByErrorMessage("不是管理员，无法登录");
            }
        }
        return response;
    }

    @RequestMapping(value = "control")
    public String controllerPage(String username,String password,HttpSession session){
        System.out.println("username="+username);
        System.out.println("password="+password);
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        //校验管理员是否已经登录，直接跳转至管理页
        if(currentUser != null && iUserService.checkAdminRole(currentUser).isSuccess()){
            return "backend/manageMain";
        }
        ServerResponse<User> response = iUserService.login(username,password);
        if(response.isSuccess()){
            User user = response.getData();
            if(user.getRole() == Const.Role.ROLE_ADMIN){
                //说明登录的是管理员
                session.setAttribute(Const.CURRENT_USER,user);
                return "backend/manageMain";
            }else{
                return "backend/manageLogin";
            }
        }
        return "backend/manageLogin";
    }

    @RequestMapping(value = "login")
    public String loginPage(){
        return "backend/manageLogin";
    }

    @RequestMapping(value = "home")
    public String homePage(){
        return "backend/manageHome";
    }
}
